package com.chenhy.config;

import com.chenhy.security.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 自定义登录注销
        http.formLogin().loginPage("/toLogin")
                .loginProcessingUrl("/login")
                .successHandler(new MyAuthenticationSuccessHandler("/index"))
                .failureForwardUrl("/loginFail");

        // 授权
        http.authorizeRequests()
                .antMatchers("/img/**", "/css/**", "/js/**", "/layui/**", "/favicon.ico", "/getCaptchaImg", "/verify")
                .permitAll()
                .antMatchers("/toLogin","/error.html")
                .permitAll()
                .anyRequest()
                .authenticated();

        // 设置为可弹窗显示
        http.headers().frameOptions().sameOrigin();

        // 权限不足异常处理
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

        // 关闭csrf
        http.csrf().disable();

        // 注销
        http.logout()
                .logoutUrl("/logout")  // 自定义退出登录url（默认/logout）
                .logoutSuccessUrl("/login.html")  // 自定义退出登录成功访问的url（默认到登陆页面）
        ;


    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
